package main

import "time"

type Hub struct {
	clients    map[*Client]bool
	register   chan *Client
	unregister chan *Client
	rooms      map[string]*HubRoom
}

type HubRoom struct {
	RoomId     string
	clients    map[*Client]bool
	register   chan *Client
	unregister chan *Client
	broadcast  chan Result //广播数据
}

func createHub() *Hub {
	return &Hub{
		register:   make(chan *Client),
		unregister: make(chan *Client),
		clients:    make(map[*Client]bool),
		rooms:      make(map[string]*HubRoom),
	}
}

func (hubRoom *HubRoom) run(callback func()) {
	tick := time.NewTimer(time.Second * 30)
	for {
		select {
		//注册
		case client := <-hubRoom.register:
			hubRoom.clients[client] = true
		//删除客户端
		case client := <-hubRoom.unregister:
			if _, ok := hubRoom.clients[client]; ok {
				delete(hubRoom.clients, client)
				close(client.send)
			}
		//发送信息
		case message := <-hubRoom.broadcast:
			for k, _ := range hubRoom.clients {
				k.send <- message
			}
		//30s之后如果没有用户，则关闭房间
		case <-tick.C:
			if len(hubRoom.clients) == 0 {
				callback()
				return
			}
		}

	}
}

// 运行
func (hub *Hub) run() {
	for {
		select {
		//注册
		case client := <-hub.register:
			hub.clients[client] = true
		//删除客户端
		case client := <-hub.unregister:
			if _, ok := hub.clients[client]; ok {
				delete(hub.clients, client)
				close(client.send)
			}
		}
	}
}
